package common

import (
	"context"
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
	"time"
)

func GetRMQConn() *amqp.Connection {
	rconn, err := amqp.Dial("amqp://admin:admin@127.0.0.1:5672/")
	if err != nil {
		log.Fatal("连接mq失败: ", err)
	}
	return rconn
}

func SendMessageTestRMQ(rconn *amqp.Connection) {
	ch, _ := rconn.Channel()
	defer ch.Close()
	//队列配置    durable 设置为true
	q, _ := ch.QueueDeclare("hello", true, false, false, false, nil)
	body := "Hello World!"
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	//发送消息
	rerr := ch.PublishWithContext(
		ctx,
		"",
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			DeliveryMode: amqp.Persistent,
			ContentType:  "text/plain",
			Body:         []byte(body),
		})
	if rerr != nil {
		log.Println("发送消息失败: ", rerr)
	}

	log.Println("发送消息成功,消息内容: ", body)

}
